<script setup lang="ts">
import RoomStatus from './components/RoomStatus.vue'
import RoomAction from './components/RoomAction.vue'
import RoomMessage from './components/RoomMessage.vue'
import { onMounted, onUnmounted } from 'vue'
import { type Socket, io } from 'socket.io-client'
import { baseURL } from '@/utils/request'
import { useUserStore } from '@/stores'
import { useRoute } from 'vue-router'
import type { Message, TimeMessages } from '@/types/room'
import { ref } from 'vue'
import { MsgType, OrderType } from '@/enum'
import type { ConsultOrderItem, Image } from '@/types/consult'
import { getConsultOrderDetail } from '@/services/consult'
import { nextTick } from 'vue'
import dayjs from 'dayjs'
import { showToast } from 'vant'
import { provide } from 'vue'

const store = useUserStore()
const route = useRoute()

// 所有的消息存放的数组
const list = ref<Message[]>([])
// 订单对象
const consult = ref<ConsultOrderItem>()

// 1. 问诊室相关操作
let socket: Socket
onMounted(() => {
  // socket = io('socket服务器的地址', {})
  // 建立socket连接
  socket = io(baseURL, {
    auth: {
      token: `Bearer ${store.user?.token}`
    },
    query: {
      orderId: route.query.orderId
    }
  })

  socket.on('connect', () => {
    // 建立连接成功
    console.log('建立连接成功')
    // 让数据数组清空
    list.value = []
  })

  socket.on('error', () => {
    // 错误异常消息
    console.log('错误异常消息')
  })

  socket.on('disconnect', () => {
    // 已经断开连接
    console.log('已经断开连接')
  })
})

onUnmounted(() => {
  // 关闭socket连接
  socket.close()
})

const initialMsg = ref(true) // 记录是否是初始的聊天消息, 是: true, 不是: false
onMounted(() => {
  // 1. 接收默认的聊天记录(每一个消息分组的所有消息前加一条时间消息)
  socket.on('chatMsgList', ({ data }: { data: TimeMessages[] }) => {
    // 1.1 定义临时数组
    const arr: Message[] = []
    // 1.2 遍历消息分组数组
    data.forEach((item, i) => {
      // 1.2.0 记录第一个消息分组的时间用于后续获取更早的消息分组
      if (i === 0) time.value = item.createTime
      // 1.2.1 创建一条时间通知消息放入数组
      arr.push({
        id: item.createTime,
        msgType: MsgType.Notify,
        createTime: item.createTime,
        msg: {
          content: item.createTime
        },
        noscroll: initialMsg.value === false
      })
      // 1.2.2 把剩余的消息放入数组
      // arr.push(...item.items)
      item.items.forEach((obj) => {
        arr.push({ noscroll: initialMsg.value === false, ...obj })
      })
    })
    // 1.3 把消息追加到总的聊天消息数组中
    list.value.unshift(...arr)
    // ---------------------------------------------
    // 1.4 关闭刷新效果
    loading.value = false
    // 1.5 判断是否还有数据
    if (data.length === 0) {
      return showToast('没有更早的聊天记录了...')
    }
    // 1.6 判断是否是初始消息
    if (initialMsg.value) {
      // 第一次获取消息, 则会进来, 需要让列表滚动到最底部
      console.log('我是第一次进来...')
      // 1.7 标明消息已读
      socket.emit('updateMsgStatus', arr[arr.length - 1].id)
      nextTick(() => {
        window.scrollTo(0, document.body.scrollHeight)
        initialMsg.value = false
      })
    }
  })
})

// 2.获取订单详情
onMounted(async () => {
  const res = await getConsultOrderDetail(route.query.orderId as string)
  consult.value = res.data
})

onMounted(() => {
  socket.on('statusChange', async () => {
    const res = await getConsultOrderDetail(route.query.orderId as string)
    consult.value = res.data
  })
})

// 发送文字消息
const sendText = (text: string) => {
  // 1.1 给socket服务器发送文字消息
  // 发送信息需要  发送人  收消息人  消息类型  消息内容
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgText,
    msg: {
      content: text
    }
  })
}

// 发送图片消息
const sendImage = (img: Image) => {
  // 1.1 给socket服务器发送文字消息
  // 发送信息需要  发送人  收消息人  消息类型  消息内容
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgImage,
    msg: {
      picture: img
    }
  })
}

// 接收服务端推送的消息
onMounted(() => {
  socket.on('receiveChatMsg', (event) => {
    // 1.1 把接收到的消息放入消息数组
    list.value.push(event)
    // 1.2 让列表滚动到最底部
    nextTick(() => {
      // 1.3 标明消息已读
      socket.emit('updateMsgStatus', event.id)
      window.scrollTo(0, document.body.scrollHeight)
    })
  })
})

// 实现下拉加载历史消息
const loading = ref(false)
const time = ref(dayjs().format('YYYY-MM-DD hh:mm:ss')) // 记录每段消息的开始时间
const onRefresh = () => {
  // 触发下拉
  socket.emit('getChatMsgList', 10, time.value, route.query.orderId)
}

// 4. 评价医生
provide('consult', consult)

const completeEva = (score: number) => {
  const item = list.value.find((obj) => obj.msgType === MsgType.CardEvaForm)
  if (item) {
    item.msgType = MsgType.CardEva
    item.msg.evaluateDoc = { score }
  }
}
provide('completeEva', completeEva)
</script>

<template>
  <div class="room-page">
    <cp-nav-bar title="问诊室" />
    <room-status
      :status="consult?.status"
      :countdown="consult?.countdown"
    ></room-status>
    <van-pull-refresh v-model="loading" @refresh="onRefresh">
      <room-message :list="list"></room-message>
    </van-pull-refresh>
    <room-action
      :disabled="consult?.status !== OrderType.ConsultChat"
      @send-text="sendText"
      @send-image="sendImage"
    ></room-action>
  </div>
</template>

<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
